package top.wilbert.collegelink.user.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.wilbert.collegelink.common.constant.AuthServerConstant;
import top.wilbert.collegelink.common.exception.BizCodeEnum;
import top.wilbert.collegelink.common.vo.UserResponseVo;
import top.wilbert.collegelink.common.vo.UserSimpleInfoVo;
import top.wilbert.collegelink.user.entity.UserEntity;
import top.wilbert.collegelink.user.feign.ThirdPartFeignService;
import top.wilbert.collegelink.user.service.UserService;
import top.wilbert.collegelink.common.utils.PageUtils;
import top.wilbert.collegelink.common.utils.R;
import top.wilbert.collegelink.user.vo.UserUpdatePasswordVo;
import top.wilbert.collegelink.user.vo.UserUpdatePhoneVo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author Augus
 * @email 2531496343@qq.com
 * @date 2022-12-23 20:02:17
 */
@RestController
@RequestMapping("/user/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 注销用户
     */
    @RequestMapping("/logOff")
    public R logOff(@RequestParam Long userId){
        userService.remove(new QueryWrapper<UserEntity>().eq("user_id",userId));
        UserEntity userEntity = new UserEntity();
        userEntity.setUserId(userId);
        userEntity.setAccountName("该用户已注销");
        userEntity.setPhone("0");
        userEntity.setAvatarUrl("https://collegelink-avatar.oss-cn-hangzhou.aliyuncs.com/2023-02-27/2575f477-83aa-4fac-8087-85e67a8d4272.jpg");
        userService.save(userEntity);

        return R.ok();
    }

    /**
     * 根据手机号发送验证码（更新密码）
     * @param phone
     * @return
     */
    @GetMapping("/sms/sendUpdatePasswordCode")
    public R sendUpdatePasswordCode(@RequestParam String phone) {
        R result = userService.smsSendCode(phone, AuthServerConstant.UPDATE_PASSWORD_CODE_CACHE_PREFIX);
        return result;
    }

    /**
     * 根据手机号发送验证码（更新手机号）
     * @param phone
     * @return
     */
    @GetMapping("/sms/sendUpdatePhoneCode")
    public R sendUpdatePhoneCode(@RequestParam String phone) {
        R result = userService.smsSendCode(phone, AuthServerConstant.UPDATE_PHONE_CODE_CACHE_PREFIX);
        return result;
    }

    /**
     * 更新手机号
     * @param userUpdatePhoneVo
     * @param request
     * @return
     */
    @RequestMapping("/updatePhone")
    public R updatePhone(@RequestBody UserUpdatePhoneVo userUpdatePhoneVo, HttpServletRequest request){
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.UPDATE_PHONE_CODE_CACHE_PREFIX + userUpdatePhoneVo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (userUpdatePhoneVo.getCode().equals(s.split("_")[0])) {
                if(userService.searchUserByPhone(userUpdatePhoneVo.getPhone()) == null){
                    UserResponseVo userResponseVo = userService.updatePhone(userUpdatePhoneVo);
                    String token = request.getHeader("token");
                    String userInfo = JSON.toJSONString(userResponseVo);
                    stringRedisTemplate.opsForValue().set(AuthServerConstant.LOGIN_USER_PREFIX + token, userInfo, 3, TimeUnit.DAYS);
                    //验证码通过，删除验证码
                    stringRedisTemplate.delete(AuthServerConstant.UPDATE_PHONE_CODE_CACHE_PREFIX + userUpdatePhoneVo.getPhone());
                    return R.ok().setData(userResponseVo);
                }else {
                    //手机号已注册
                    return R.error(BizCodeEnum.USER_UPDATE_PHONE_EXCEPTION.getCode(), BizCodeEnum.USER_UPDATE_PHONE_EXCEPTION.getMessage());
                }
            } else {
                //验证码错误
                return R.error(BizCodeEnum.VERIFY_CODE_EXCEPTION.getCode(), BizCodeEnum.VERIFY_CODE_EXCEPTION.getMessage());
            }
        } else {
            //验证码未发送
            return R.error(BizCodeEnum.SEND_CODE_EXCEPTION.getCode(), BizCodeEnum.SEND_CODE_EXCEPTION.getMessage());
        }
    }

    /**
     * 加密更新用户密码
     * @param userUpdatePasswordVo
     * @return
     */
    @RequestMapping("/updatePassword")
    public R updatePassword(@RequestBody UserUpdatePasswordVo userUpdatePasswordVo){
        System.out.println(userUpdatePasswordVo.toString());
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.UPDATE_PASSWORD_CODE_CACHE_PREFIX + userUpdatePasswordVo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (userUpdatePasswordVo.getCode().equals(s.split("_")[0])) {
                userService.setPassword(userUpdatePasswordVo);
                //验证码通过，删除验证码
                stringRedisTemplate.delete(AuthServerConstant.UPDATE_PASSWORD_CODE_CACHE_PREFIX + userUpdatePasswordVo.getPhone());
                return R.ok();
            } else {
                //验证码错误
                return R.error(BizCodeEnum.VERIFY_CODE_EXCEPTION.getCode(), BizCodeEnum.VERIFY_CODE_EXCEPTION.getMessage());
            }
        } else {
            //验证码未发送
            return R.error(BizCodeEnum.SEND_CODE_EXCEPTION.getCode(), BizCodeEnum.SEND_CODE_EXCEPTION.getMessage());
        }
    }

    /**
     * 修改头像：上传头像到阿里云，地址保存在数据库
     * @param avatar
     * @return
     */
    @PostMapping("/uploadAvatar")
    public R uploadAvatar(@RequestPart("avatar") MultipartFile avatar, @RequestParam Long userId, HttpServletRequest request) {
        String avatarUrl = thirdPartFeignService.uploadAvatar(avatar);
        UserResponseVo userResponseVo = userService.uploadAvatar(avatarUrl, userId);
        String token = request.getHeader("token");
        String userInfo = JSON.toJSONString(userResponseVo);
        stringRedisTemplate.opsForValue().set(AuthServerConstant.LOGIN_USER_PREFIX + token, userInfo, 3, TimeUnit.DAYS);
        return R.ok().setData(userResponseVo);
    }

    /**
     * 修改个人信息
     */
    @RequestMapping("/updateInfo")
    public R updateInfo(@RequestBody UserEntity user, HttpServletRequest request) {
        userService.updateById(user);
        UserEntity userEntity = userService.getById(user.getUserId());
        UserResponseVo userResponseVo = new UserResponseVo();
        BeanUtils.copyProperties(userEntity, userResponseVo);
        String token = request.getHeader("token");
        String userInfo = JSON.toJSONString(userResponseVo);
        stringRedisTemplate.opsForValue().set(AuthServerConstant.LOGIN_USER_PREFIX + token, userInfo, 3, TimeUnit.DAYS);
        return R.ok().setData(userResponseVo);
    }

    /**
     * 根据手机号查找用户
     * @param phone
     * @return
     */
    @RequestMapping("/searchUserByPhone")
    public UserResponseVo searchUserByPhone(String phone) {
        UserResponseVo userResponseVo = userService.searchUserByPhone(phone);

        return userResponseVo;
    }

    /**
     * 根据id查找用户详细信息
     */
    @RequestMapping("/searchUserById")
    public UserResponseVo searchUserById(@RequestParam("userId") Long userId) {
        UserEntity user = userService.getById(userId);
        UserResponseVo userResponseVo = new UserResponseVo();
        BeanUtils.copyProperties(user, userResponseVo);

        return userResponseVo;
    }

    /**
     * 根据ids查找用户信息简单显示列表
     */
    @RequestMapping("/searchUserByIds")
    public Map<Long, UserSimpleInfoVo> searchUserByIds(@RequestParam("userIds") List<Long> userIds) {
        Collection<UserEntity> userEntities = userService.listByIds(userIds);
        HashMap<Long, UserSimpleInfoVo> map = new HashMap<>();
        for (UserEntity userEntity : userEntities) {
            UserSimpleInfoVo userSimpleInfoVo = new UserSimpleInfoVo();
            BeanUtils.copyProperties(userEntity, userSimpleInfoVo);
            map.put(userEntity.getUserId(),userSimpleInfoVo);
        }
        return map;
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
//    @RequiresPermissions("user:user:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = userService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{userId}")
//    @RequiresPermissions("user:user:info")
    public R info(@PathVariable("userId") Long userId) {
        UserEntity user = userService.getById(userId);

        return R.ok().put("user", user);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
//    @RequiresPermissions("user:user:save")
    public R save(@RequestBody UserEntity user) {
        userService.save(user);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("user:user:update")
    public R update(@RequestBody UserEntity user) {
        userService.updateById(user);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
//    @RequiresPermissions("user:user:delete")
    public R delete(@RequestBody Long[] userIds) {
        userService.removeByIds(Arrays.asList(userIds));

        return R.ok();
    }

}
